package concurrency;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by sunzhengjie on 2017/1/20.
 */
public class Sender implements Runnable{
    private Random random = new Random();
    private PipedWriter out = new PipedWriter();
    public PipedWriter getWriter(){
        return out;
    }

    @Override
    public void run() {
        try{
            while(true){
                for(char c = 'A';c <= 'z'; c++){
                    out.write(c);
                    TimeUnit.MICROSECONDS.sleep(random.nextInt(500));
                }
            }
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }
    }

    static class Receiver implements Runnable{
        private PipedReader in;
        public Receiver(Sender sender) throws IOException {
            in = new PipedReader(sender.getWriter());
        }

        @Override
        public void run() {
            try{
                while(true){
                    System.out.println("Read: " + (char)in.read() + ". ");
                }
            } catch (IOException e) {
               System.out.println(e + "Receiver read Exception");
            }
        }
    }

    public static void main(String[] arg0) throws IOException, InterruptedException {
        Sender sender = new Sender();
        Receiver receiver = new Receiver(sender);
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(sender);
        exec.execute(receiver);
        TimeUnit.SECONDS.sleep(4);
        exec.shutdownNow();
    }
}
